package com.ict.interceptor;

import com.ict.util.RSAUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.security.PublicKey;


public class SignatureValidationInterceptor implements HandlerInterceptor {

    private final PublicKey publicKey; // 服务端的公钥
    private static final long ALLOWED_TIME_WINDOW = 5 * 60 * 1000; // 允许的时间窗口（5分钟）

    public SignatureValidationInterceptor(PublicKey publicKey) {
        this.publicKey = publicKey;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的签名、nonceId和时间戳
        String signature = request.getHeader("Signature");
        String nonceId = request.getHeader("NonceId");
        String timestampStr = request.getHeader("Timestamp");

        if (signature == null || nonceId == null || timestampStr == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        // 验证时间戳是否在允许的时间窗口内
        long timestamp = Long.parseLong(timestampStr);
        long currentTime = System.currentTimeMillis();
        if (Math.abs(currentTime - timestamp) > ALLOWED_TIME_WINDOW) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }


        // 获取请求数据
        URI uri = new URI(request.getRequestURI());
        String data = uri + nonceId + timestamp;

        // 验证签名
        boolean isValid = RSAUtil.verify(data, signature, publicKey);

        if (!isValid) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        return true; // 继续执行请求
    }
}
